using System;
using System.Collections.Generic;
using System.Text;

namespace AAM.BIZ
{
    [Serializable]
    public class Key
    {

        private ObjectType type;
        private object[] values;

        public Key(ObjectType type, object[] values)
        {
            Tools.Util.CheckObject(type);
            Tools.Util.CheckObject(values);
            this.type = type;
            this.values = new object[values.Length];
            for(int c=0;c<values.Length;c++)
            {
                this.values[c] = values[c];
            }
        }

        public ObjectType Type { get { return type; } }
        public int Length { get { return values.Length; } }

        public object this[int index]
        {
            get { return values[index]; }
            set { values[index] = value; }
        }

        public override bool Equals(object obj)
        {
            if (!(obj is Key)) return false;
            Key other = (Key)obj;
            if (!type.Equals(other.type)) return false;
            if (Length != other.Length) return false;
            for (int c = 0; c < Length; c++)
            {
                object o1,o2;
                o1 = values[c];
                o2 = other.values[c];
                if (o1 == null && o2 != null) return false;
                if (o1 != null && o2 == null) return false;
                if (o1 != null && o2 != null && !o1.Equals(o2)) return false;
            }
            return true;
        }

        public override int GetHashCode()
        {
            int hash = type.GetHashCode();
            for (int c = 0; c < Length; c++)
            {
                object o = values[c];
                hash *= 31;
                if(o != null) hash += o.GetHashCode();
            }
            return hash;
        }

        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(type.ToString());
            builder.Append('[');
            for (int c = 0; c < Length; c++)
            {
                if (c != 0) builder.Append(',');
                builder.Append(values[c].ToString());
            }
            builder.Append(']');
            return builder.ToString();
        }

    }
}
